<?php


namespace Extentions\mysql;

use core\lib\Config;

class Db{
   public $dbconfig = null;

   private static $instance = null;

   private $coon = null;

   public $insertid = null;

   public $effect = null;

   public $err;

   private function __construct($parm)
   {
       $this->dbconfig = Config::all("mysql");

       $this->dbconfig = array_merge($this->dbconfig,$parm);

       $this -> connect();
   }

   private function __clone()
   {
       // TODO: Implement __clone() method.
   }

   public static function instance(){
       if(!self::$instance instanceof self){
           self::$instance = new self($parm = []);
       }
       return self::$instance;
   }

   private function connect(){
       try{
           $dsn = "{$this->dbconfig["db"]}:host={$this->dbconfig['host']};
           port={$this->dbconfig['port']};dbname={$this->dbconfig['dbname']};
           charset={$this->dbconfig['charset']}";

           $this->coon=new \PDO($dsn,$this->dbconfig['user'],$this->dbconfig['passwd']);
           $this->coon->query("SET NEMES {$this->dbconfig['charset']}");
       }catch (\Exception $e){
           $this->err=$e->getMessage().$e->getCode();
           die($this->err);
       }
   }

   public function exec($sql){
       $num = $this->coon->exec($sql);
       if($num > 0){
           if(null !== $this->coon->$this->coon->lastInsertId()){
               $this->insertid = $this->coon->lastInsertId();
           }
           $this->effect = $num;
       }else{
           $this->err = $this->coon->errorInfo().$this->coon->errorCode();
       }

       return $num;
   }

   public function query($sql){
       return $this->coon->query($sql)->fetchAll();
   }

   public function fetch($sql){

       try{
           return $this->coon->query($sql)->fetch(\PDO::FETCH_ASSOC);
       }catch (\Exception $e){
           $this->err = $e->getCode().$e->getMessage();
       }
   }

   public function fetchall($sql){
       try{
           $temp = $this->coon->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
           return $temp;

       }catch (\Exception $e){
           $this->err = $e->getCode().$e->getMessage();
       }
   }

   public function pre_exec($sql,$query,$f=null){
       $temp = $this->coon->prepare($sql);
       $temp->execute($query);
       return $temp->fetchAll($f);
   }

}

